﻿Imports MindFusion.Diagramming
Imports amod2

Public Class ClsFileAmod
    Inherits ClsFile
    'represents aMod file

#Region "Attributes"
#Region "Private attributes"
    Private MoDat As Dat = New Dat
    'Private MoDat.DsAmod As DsAmod = New DsAmod 'aMod dataset
    Private MiActualVID As Integer = -1 'actual version ID of aMod which is processed
    Private MbFileWasModified As Boolean = True 'indicates if file was modified since last save    
#End Region
#End Region
#Region "Constructors"
    Sub New()
        MyBase.New()
    End Sub

    Sub New(ByVal IsPath As String)
        MyBase.New(IsPath)
    End Sub
#End Region
#Region "Properties"
#Region "Public attributes"
    Public Property Dat() As Dat
        Get
            Return MoDat
        End Get
        Set(ByVal IoValue As Dat)
            MoDat = IoValue
        End Set
    End Property
    Public ReadOnly Property Dataset() As DsAmod
        Get
            Return MoDat.DsAmod
        End Get
    End Property
    Public ReadOnly Property ActualVID() As Integer
        Get
            Return MiActualVID
        End Get
    End Property
    Public Property FileWasModified() As Boolean
        Get
            Return MbFileWasModified
        End Get
        Set(ByVal IbValue As Boolean)
            If MbFileWasModified <> IbValue Then
                MbFileWasModified = IbValue

                'raise event only if file is in open satte
                If MeStateOfFile = GeFileState.kkOpened Then RaiseEvent MMFileWasChangedToValue(MbFileWasModified)
            End If
        End Set
    End Property
#End Region
#End Region
#Region "Events"
    Public Event MMFileWasChangedToValue(ByVal Value As Boolean) 'event is raised after value MbFileWasChanged was changed
#End Region
#Region "Functions"
#Region "Open file&DS, Save file&DS, Close file&DS"
    'open dataset
    Private Function OpenDataset() As GeActionResult
        Try
            If MeStateOfFile = GeFileState.kkReady Then
                If MoDat.LoadAmod(MsPath) Then
                    Return GeActionResult.kkOk
                Else
                    Throw New Exception
                End If
            Else
                Debug.Print("CHYBA!!! - ClsFileAmod.OpenDataset")
                Throw New Exception
            End If
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'save dataset
    Private Function SaveDataset() As GeActionResult
        Try
            If MeStateOfFile = GeFileState.kkOpened Then
                If MoDat.SaveAmod(MsPath) Then
                    Return GeActionResult.kkOk
                Else
                    Throw New Exception
                End If
                Debug.Print("CHYBA!!! - ClsFileAmod.SaveDataset")
                Throw New Exception
            End If
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'new file
    Public Function CreateNewFile() As GeActionResult
        Try
            If MeStateOfFile = GeFileState.kkNotInit Then
                MeStateOfFile = GeFileState.kkNewFile
                Dim LiNewVID As Integer = -1 '-1 is default value
                MoDat.DsAmod.Clear()
                MsPath = ""
                CreateNewVersion(LiNewVID)
                If MiActualVID = -1 Then
                    MiActualVID = LiNewVID
                Else
                    Debug.Print("CHYBA!!! - ClsFileAmod.NewFile")
                End If
                FileWasModified = True
                Return GeActionResult.kkOk
            Else
                Debug.Print("CHYBA!!! - ClsFileAmod.NewFile")
                Throw New Exception
            End If
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'init after new file
    Public Function InitAfterNewFile(ByVal IsPath As String) As GeActionResult
        Try
            If MeStateOfFile = GeFileState.kkNewFile Then
                MeStateOfFile = GeFileState.kkOpened
                MsPath = IsPath
                Return GeActionResult.kkOk
            Else
                Debug.Print("CHYBA!!! - ClsFileAmod.InitAfterNewFile")
                Throw New Exception
            End If
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'open file
    Public Overrides Function OpenFile() As GeActionResult
        Try
            If MyBase.OpenFile = GeActionResult.kkOk Then
                If OpenDataset() = GeActionResult.kkOk Then
                    MeStateOfFile = GeFileState.kkOpened
                    MiActualVID = GetLastVersion()
                    FileWasModified = False
                    Return GeActionResult.kkOk
                Else
                    Throw New Exception
                End If
            Else
                Debug.Print("CHYBA!!! - ClsFileAmod.OpenFile")
                Throw New Exception
            End If
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'save file
    Public Function SaveFile() As GeActionResult
        Try
            If MeStateOfFile = GeFileState.kkOpened Then
                If SaveDataset() = GeActionResult.kkOk Then
                    FileWasModified = False
                    Return GeActionResult.kkOk
                Else
                    Throw New Exception
                End If
            Else
                Debug.Print("CHYBA!!! - ClsFileAmod.SaveFile")
                Throw New Exception
            End If
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'close file
    Public Overrides Function CloseFile() As GeActionResult
        Try
            If MyBase.CloseFile = GeActionResult.kkOk Then
                MeStateOfFile = GeFileState.kkNotInit
                MoDat.DsAmod.Clear()
                MsPath = ""
                MiActualVID = -1
                FileWasModified = True
                Return GeActionResult.kkOk
            Else
                Debug.Print("CHYBA!!! - ClsFileAmod.CloseFile")
                Throw New Exception
            End If
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
#End Region
#Region "Manipulating with DS"
#Region "INSERT"
    'insert new version to table _a_Version
    Public Function InsertNewVersion(ByRef IiNewVID As Int32) As GeActionResult
        Try
            Dim LoRow As DataRow
            Dim LsTableName As String = DsAMod.TableSysnames.Version.Name
            LoRow = MoDat.DsAMod.Tables(LsTableName).NewRow() '"_a_Version"
            LoRow(DsAMod.TableSysnames.ColumnName_VID) = IiNewVID '"_a_VID"
            LoRow(DsAMod.TableSysnames.Version.Columns.Created) = System.DateTime.Now() '"_a_Created"
            LoRow(DsAMod.TableSysnames.Version.Columns.Description) = GsStringNullValue '"_a_Description"

            MoDat.DsAMod.Tables(LsTableName).Rows.Add(LoRow) '"_a_Version"

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'insert new version to table _Settings
    Public Function InsertNewSettings(ByRef IiNewVID As Integer) As GeActionResult
        Try
            Dim LoRow As DataRow

            LoRow = MoDat.DsAmod.Tables("_Settings").NewRow()
            LoRow("_a_VID") = IiNewVID
            LoRow("Version") = 25
            LoRow("xModType") = 0

            MoDat.DsAmod.Tables("_Settings").Rows.Add(LoRow)

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'insert new diagram to table _a_FlowChartData
    Public Function InsertNewDiagramData(ByVal IiNewVID As Integer) As GeActionResult
        Try
            Dim LoRow As DataRow = MoDat.DsAmod.Tables("_a_FlowChartData").NewRow
            LoRow("_a_VID") = IiNewVID
            LoRow("_a_Value") = GsStringNullValue

            MoDat.DsAmod.Tables("_a_FlowChartData").Rows.Add(LoRow)

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'insert new table to table _Tables
    Public Function InsertNewTable(ByVal IsOriginalAppTableName As String, ByVal IsUnitName As String, ByRef OsNewAppTableName As String) As GeActionResult
        Try
            Dim LoRow As DataRow
            Dim LsNewAppTableName As String = GetNextUniqueNameOfTable(IsOriginalAppTableName)
            OsNewAppTableName = LsNewAppTableName

            LoRow = MoDat.DsAmod.Tables("_Tables").NewRow()
            LoRow("TableName") = GetTableNameFromAppTableName(LsNewAppTableName)
            LoRow("_a_VID") = MiActualVID
            LoRow("AppTableName") = LsNewAppTableName
            LoRow("_a_UnitName") = IsUnitName
            LoRow("_a_IsSupport") = False
            LoRow("_a_Sort") = GiIntegerDefaultValue
            LoRow("_a_Description") = GsStringNullValue

            MoDat.DsAmod.Tables("_Tables").Rows.Add(LoRow)

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'insert new table to table _Hierarchy
    Public Function InsertNewTableToHierarchy(ByVal IsAppTableName As String) As GeActionResult
        Try
            Dim LoRow As DataRow

            Dim LoRows() As DataRow = MoDat.DsAmod.Tables("_Hierarchy").Select
            If LoRows.Length = 0 Then
                'insert new data to  table _Options
                If InsertNewOptions(IsAppTableName) <> GeActionResult.kkOk Then Throw New Exception
            End If

            LoRows = MoDat.DsAmod.Tables("_Hierarchy").Select("TableName='" & IsAppTableName & "'")
            If LoRows.Length = 0 Then
                LoRow = MoDat.DsAmod.Tables("_Hierarchy").NewRow()
                LoRow("HierarchyName") = GetMainHierarchyName()
                LoRow("_a_VID") = MiActualVID
                LoRow("TableName") = IsAppTableName
                LoRow("ParentTable") = GsStringNullValue
                LoRow("ForeignKey") = GsStringNullValue
                LoRow("RelationType") = kkRelationTypes.kk_1_n
                LoRow("IsUnderView") = False
                LoRow("UnderViewName") = GsStringNullValue
                LoRow("IncludeXmodName") = GsStringNullValue
                LoRow("IsMainInIncludeXmod") = False

                MoDat.DsAmod.Tables("_Hierarchy").Rows.Add(LoRow)
            Else
                Throw New Exception
            End If

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'insert new relationship  to table _Hierarchy
    Public Function InsertNewRelationshipToHierarchy(ByVal IsParentAppTableName As String, ByVal IsChildTableName As String, ByVal IeRelationType As kkRelationTypes) As GeActionResult
        Try
            Dim LoRows() = MoDat.DsAmod.Tables("_Hierarchy").Select("TableName='" & IsChildTableName & "'")
            LoRows(0)("ParentTable") = IsParentAppTableName
            LoRows(0)("ForeignKey") = GetForeignKeyForHierarchy(IsParentAppTableName)
            LoRows(0)("RelationType") = IeRelationType

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'insert new column to table _a_Columns (data are provided)
    Public Function InsertNewColumn(ByVal IsAppTableName As String, ByVal IsOriginalColumnName As String, ByRef OsNewColumnName As String, ByVal IiPositionOfColumn As Integer) As GeActionResult
        Try
            Dim LoRow As DataRow
            Dim LsNewColumnName As String = GetNextUniqueNameOfColumn(IsAppTableName, IsOriginalColumnName)
            OsNewColumnName = LsNewColumnName

            LoRow = MoDat.DsAmod.Tables("_a_Columns").NewRow()
            LoRow("Tablename") = GetTableNameFromAppTableName(IsAppTableName)
            LoRow("ColumnName") = LsNewColumnName
            LoRow("_a_ColumnType") = kkXmodColumnTypes.kkBoolean 'boolean
            LoRow("Access") = kkXmodAccessTypes.kkRW  'R/W
            LoRow("_a_VID") = MiActualVID
            LoRow("DefaultValue") = GsStringNullValue
            LoRow("MaxValue") = 1000000
            LoRow("MinValue") = 0
            LoRow("Position") = IiPositionOfColumn
            LoRow("SortColumn") = GiIntegerDefaultValue
            LoRow("GroupColor") = GiIntegerDefaultValue
            LoRow("SharedJoinedModule") = GiIntegerDefaultValue
            LoRow("ResValue") = LsNewColumnName
            LoRow("_a_Sort") = GiIntegerDefaultValue
            LoRow("_a_Description") = GsStringNullValue
            LoRow("_a_ComponentType") = kkComponentTypes.kkNone 'none
            LoRow("_a_TabName") = GsStringNullValue

            Dim LoRow2() As DataRow
            LoRow2 = GetColumnsOfTableWithCondition(IsAppTableName, "System='1'")
            If LoRow2.Length = 0 Then
                LoRow("System") = 1
            End If

            MoDat.DsAmod.Tables("_a_Columns").Rows.Add(LoRow)

            'updating positions of columns
            Dim LoRowsOtherColumns() = GetColumnsOfTableWithCondition(IsAppTableName, "Position>=" & IiPositionOfColumn)
            For Each LoDataRow As DataRow In LoRowsOtherColumns
                If LoDataRow.Item("ColumnName") <> LsNewColumnName Then LoDataRow.Item("Position") += 1
            Next

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'insert new column to table _a_Columns (row is provided)
    Public Function InsertNewColumn(ByRef OoRow As DataRow) As GeActionResult
        Try
            MoDat.DsAmod.Tables("_a_Columns").Rows.Add(OoRow)

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'insert new Unit to table _ModulStructure
    Public Function InsertNewUnit(ByVal IsOriginalUnitName As String, ByRef OsNewUnitName As String) As GeActionResult
        Try
            Dim LoRow As DataRow
            Dim LsNewUnitName As String = GetNextUniqueNameOfUnit(IsOriginalUnitName)
            OsNewUnitName = LsNewUnitName

            LoRow = MoDat.DsAmod.Tables("_ModulStructure").NewRow()
            LoRow("UnitName") = LsNewUnitName
            LoRow("_a_VID") = MiActualVID
            'LoRow("ParentUnit") = GsStringNullValue
            'LoRow("LogName") = GsStringNullValue
            'LoRow("Tables") = GsStringNullValue
            'LoRow("Forms") = GsStringNullValue
            'LoRow("_a_Description") = GsStringNullValue

            MoDat.DsAmod.Tables("_ModulStructure").Rows.Add(LoRow)

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'insert options to table _Options
    Public Function InsertNewOptions(ByVal IsTableName As String) As GeActionResult
        Try
            Dim LoRow As DataRow

            LoRow = MoDat.DsAmod.Tables("_Options").NewRow()
            LoRow("TableName") = GetTableNameFromAppTableName(IsTableName)
            LoRow("_a_VID") = MiActualVID
            LoRow("ViewName") = ""
            LoRow("SupportTableName") = ""
            LoRow("ShowAll") = True

            MoDat.DsAmod.Tables("_Options").Rows.Add(LoRow)

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
#End Region
#Region "UPDATE"
    'update diagram in table _a_FlowChartData
    Public Function UpdateDiagramData(ByVal IsDiagramData As String) As GeActionResult
        Try
            Dim LoRows() As DataRow = MoDat.DsAmod.Tables("_a_FlowChartData").Select(GetActualVIDcondition())
            LoRows(0)("_a_Value") = IsDiagramData

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'update description of actual version
    Public Function UpdateDescriptionOfActualVersion(ByVal IsDescription As String) As GeActionResult
        Try
            Dim LoRows() = GetActualVersion()
            LoRows(0)("_a_Description") = IsDescription

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'update description of unit
    Public Function UpdateDescriptionOfUnit(ByVal IsUnitName As String, ByVal IsDescription As String) As GeActionResult
        Try
            Dim LoRows() = GetUnit(IsUnitName)
            LoRows(0)("_a_Description") = IsDescription

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'update description of table 
    Public Function UpdateDescriptionOfTable(ByVal IsAppTableName As String, ByVal IsDescription As String) As GeActionResult
        Try
            Dim LoRows() = GetTable(IsAppTableName)
            LoRows(0)("_a_Description") = IsDescription

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'update - move column up in table _a_Columns
    Public Function UpdateUpColumnPosition(ByVal IsAppTableName As String, ByVal IsColumnName As String, ByRef OiNewColumnPosition As Integer) As GeActionResult
        Try
            Dim LoRows() = GetConcreteColumn(IsAppTableName, IsColumnName)
            Dim LiPositionOfChanging As Integer = LoRows(0).Item("Position")

            If LiPositionOfChanging > 1 Then
                Dim LoRowsUpColumn() = GetColumnsOfTableWithCondition(IsAppTableName, "Position=" & LiPositionOfChanging - 1)
                LoRowsUpColumn(0)("Position") += 1
                LoRows(0)("Position") -= 1
                OiNewColumnPosition = LoRows(0)("Position")

                FileWasModified = True
                Return GeActionResult.kkOk
            Else
                Debug.Print("CHYBA!!! - UpdateUpColumnPosition")
                Return GeActionResult.kkError
            End If
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'update - move column down in table _a_Columns
    Public Function UpdateDownColumnPosition(ByVal IsAppTableName As String, ByVal IsColumnName As String, ByRef OiNewColumnPosition As Integer) As GeActionResult
        Try
            Dim LoRows() = GetConcreteColumn(IsAppTableName, IsColumnName)
            Dim LiPositionOfChanging As Integer = LoRows(0).Item("Position")

            If LiPositionOfChanging < GetNumberOfColumns(IsAppTableName) Then
                Dim LoRowsDownColumn() = GetColumnsOfTableWithCondition(IsAppTableName, "Position=" & LiPositionOfChanging + 1)
                LoRowsDownColumn(0)("Position") -= 1
                LoRows(0)("Position") += 1
                OiNewColumnPosition = LoRows(0)("Position")

                FileWasModified = True
                Return GeActionResult.kkOk
            Else
                Debug.Print("CHYBA!!! - UpdateDownColumnPosition")
                Return GeActionResult.kkError
            End If
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'update parent of relationship in hierarchy
    Public Function UpdateParentOfRelationshipInHierarchy(ByVal IsParentTableName As String, ByVal IsChildTableName As String, ByVal IsNewParentTableName As String) As GeActionResult
        Try
            Dim LoRows() = MoDat.DsAmod.Tables("_Hierarchy").Select("ParentTable='" & IsParentTableName & "' AND TableName='" & IsChildTableName & "'")
            LoRows(0)("ParentTable") = IsNewParentTableName
            LoRows(0)("ForeignKey") = GetForeignKeyForHierarchy(IsNewParentTableName)

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    '' ''update child of relationship in hierarchy
    ' ''Public Function UpdateChildOfRelationshipInHierarchy(ByVal IsParentTableName As String, ByVal IsChildTableName As String, ByVal IsNewChildTableName As String) As GeActionResult
    ' ''    Dim LeResult As GeActionResult
    ' ''    Try
    ' ''        LeResult = UpdateParentOfRelationshipInHierarchy(IsParentTableName, IsChildTableName, GsStringNullValue)
    ' ''        If LeResult = GeActionResult.kkOk Then
    ' ''            LeResult = InsertNewRelationshipToHierarchy(IsParentTableName, IsNewChildTableName)
    ' ''        End If

    ' ''        FileWasModified = True
    ' ''        Return LeResult
    ' ''    Catch ex As Exception
    ' ''        Return GeActionResult.kkError
    ' ''    End Try
    ' ''End Function
#End Region
#Region "DELETE"
    'delete column from _a_Columns
    Public Function DeleteColumn(ByVal IsAppTableName As String, ByVal IsColumnName As String) As GeActionResult
        Try
            Dim LoRows() = GetConcreteColumn(IsAppTableName, IsColumnName)
            Dim LiPositionOfDeleted As Integer = LoRows(0).Item("Position")
            LoRows(0).Delete()
            'setting new position for other columns with higher position than deleted column
            Dim LoRowsOtherColumns() = GetColumnsOfTableWithCondition(IsAppTableName, "Position>" & LiPositionOfDeleted)
            For Each LoDataRow As DataRow In LoRowsOtherColumns
                LoDataRow.Item("Position") -= 1
            Next

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'delete relationship from _Hierarchy (it means changing data in table _Hierarchy)
    Public Function DeleteRelationShipFromHierarchy(ByVal IsParentTableName As String, ByVal IsChildTableName As String) As GeActionResult
        Dim LeResult As GeActionResult
        Try
            LeResult = UpdateParentOfRelationshipInHierarchy(IsParentTableName, IsChildTableName, GsStringNullValue)

            FileWasModified = True
            Return LeResult
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'delete table from _Tables
    Public Function DeleteTable(ByVal IsAppTableName As String) As GeActionResult
        Dim LeResult As GeActionResult
        Try
            LeResult = DeleteTableFromHierarchy(IsAppTableName)
            If LeResult = GeActionResult.kkOk Then
                Dim LoRows() = GetTable(IsAppTableName)
                LoRows(0).Delete()
            End If

            FileWasModified = True
            Return LeResult
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'delete table from _Hierarchy
    Public Function DeleteTableFromHierarchy(ByVal IsAppTableName As String) As GeActionResult
        Try
            Dim LoRows() = MoDat.DsAmod.Tables("_Hierarchy").Select("TableName='" & IsAppTableName & "'")
            LoRows(0).Delete()

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'delete Unit from _ModulStructure
    Public Function DeleteUnit(ByVal IsUnitName As String) As GeActionResult
        Dim LoRows() As DataRow
        Try
            LoRows = GetUnit(IsUnitName)
            LoRows(0).Delete()

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
#End Region
#Region "SELECT"
    'gets last VID if exists, otherwise return 0
    Public Function GetLastVersion() As Integer
        Try
            Dim LoRows() As DataRow = MoDat.DsAmod.Tables("_a_Version").Select("_a_VID = Max(_a_VID)")
            If LoRows.Length = 0 Then
                Return 0
            Else
                Return LoRows(0).Item("_a_VID")
            End If
        Catch ex As Exception
            Debug.Print("CHYBA!!! - ClsFileAmod.GetLastVersion")
            Return -1 'default
        End Try
    End Function
    'gets next unique name of table in mask "BaseName_Index" - Name=string, Index=number
    Public Function GetNextUniqueNameOfTable(ByVal IsOriginalAppTableName As String) As String
        Try
            Dim LsFirstPart As String = ""
            Dim LiIndex As Integer = 1
            Dim LbIsNumbering = True
            Dim LsNewAppTableName As String = ""
            Dim LoRows() As DataRow

            'GetParsingStringsForUniqueName(IsOriginalAppTableName, LsFirstPart, LiIndex, LbIsNumbering)
            LoRows = GetTable(IsOriginalAppTableName)
            If LoRows.Length = 0 Then
                Return IsOriginalAppTableName
            Else
                '50x checking for unique AppTableName
                For LiI As Integer = 1 To 50
                    LsNewAppTableName = IsOriginalAppTableName & "_" & LiIndex.ToString
                    LoRows = GetTable(LsNewAppTableName)
                    If LoRows.Length = 0 Then Return LsNewAppTableName
                    LiIndex += 1
                Next
            End If

            'after unsuccessful attempts return original name
            Return IsOriginalAppTableName
        Catch ex As Exception
            'on error return original name
            Return IsOriginalAppTableName
        End Try
    End Function
    'gets next unique name of column in mask "BaseName_Index" - Name=string, Index=number
    Public Function GetNextUniqueNameOfColumn(ByVal IsAppTableName As String, ByVal IsOriginalColumnName As String) As String
        Try
            Dim LsFirstPart As String = ""
            Dim LiIndex As Integer = 1
            Dim LbIsNumbering = True
            Dim LsNewColumnName As String = ""
            Dim LoRows() As DataRow

            'GetParsingStringsForUniqueName(IsOriginalColumnName, LsFirstPart, LiIndex, LbIsNumbering)
            LoRows = GetConcreteColumn(IsAppTableName, IsOriginalColumnName)
            If LoRows.Length = 0 Then
                Return IsOriginalColumnName
            Else
                '50x checking for unique AppTableName
                For LiI As Integer = 1 To 50
                    LsNewColumnName = IsOriginalColumnName & "_" & LiIndex.ToString
                    LoRows = GetConcreteColumn(IsAppTableName, LsNewColumnName)
                    If LoRows.Length = 0 Then Return LsNewColumnName
                    LiIndex += 1
                Next
            End If

            'after unsuccessful attempts return original name
            Return IsOriginalColumnName
        Catch ex As Exception
            'on error return original name
            Return IsOriginalColumnName
        End Try
    End Function
    'gets next unique name of Unit in mask "BaseName_Index" - Name=string, Index=number
    Public Function GetNextUniqueNameOfUnit(ByVal IsOriginalUnitName As String) As String
        Try
            Dim LsFirstPart As String = ""
            Dim LiIndex As Integer = 1
            Dim LbIsNumbering = True
            Dim LsNewUnitName As String = ""
            Dim LoRows() As DataRow

            'GetParsingStringsForUniqueName(IsOriginalUnitName, LsFirstPart, LiIndex, LbIsNumbering)
            LoRows = GetUnit(IsOriginalUnitName)
            If LoRows.Length = 0 Then
                Return IsOriginalUnitName
            Else
                '50x checking for unique AppTableName
                For LiI As Integer = 1 To 50
                    LsNewUnitName = IsOriginalUnitName & "_" & LiIndex.ToString
                    LoRows = GetUnit(LsNewUnitName)
                    If LoRows.Length = 0 Then Return LsNewUnitName
                    LiIndex += 1
                Next
            End If

            'after unsuccessful attempts return original name
            Return IsOriginalUnitName
        Catch ex As Exception
            'on error return original name
            Return IsOriginalUnitName
        End Try
    End Function
    'gets number of columns for table from table _a_Columns
    Public Function GetNumberOfColumns(ByVal IsAppTableName) As Integer
        Dim LiNumberOfColumns As Integer = -1 'default value
        Try
            'here I can check max value of Position or count of items in table _a_Columns. I should get the same result :-)
            Dim LoRows() As DataRow = MoDat.DsAmod.Tables("_a_Columns").Select("Tablename='" & GetTableNameFromAppTableName(IsAppTableName) & "' AND " & GetActualVIDcondition())
            LiNumberOfColumns = LoRows.Length

        Catch ex As Exception
            Debug.Print("CHYBA!!! - GetNumberOfColumns")
        End Try
        Return LiNumberOfColumns
    End Function
    'gets actual version
    Public Function GetActualVersion() As DataRow()
        Try
            Return MoDat.DsAmod.Tables("_a_Version").Select(GetActualVIDcondition)
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    'gets unit
    Public Function GetUnit(ByVal IsUnitName As String) As DataRow()
        Try
            Return MoDat.DsAmod.Tables("_ModulStructure").Select("UnitName='" & IsUnitName & "' AND " & GetActualVIDcondition())
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    'gets table
    Public Function GetTable(ByVal IsAppTableName As String) As DataRow()
        Try
            Return MoDat.DsAmod.Tables("_Tables").Select("TableName='" & GetTableNameFromAppTableName(IsAppTableName) & "' AND AppTableName='" & IsAppTableName & "' AND" & GetActualVIDcondition())
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    'gets columns of table
    Public Function GetColumnsOfTable(ByVal IsAppTableName As String, Optional ByVal IsSortingCondition As String = "") As DataRow()
        Try
            Return MoDat.DsAmod.Tables("_a_Columns").Select("Tablename='" & GetTableNameFromAppTableName(IsAppTableName) & "' AND " & GetActualVIDcondition(), IsSortingCondition)
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    'gets columns of table with any condition
    Public Function GetColumnsOfTableWithCondition(ByVal IsAppTableName As String, ByVal IsCondition As String, Optional ByVal IsSortingCondition As String = "") As DataRow()
        Try
            Dim LsCondition As String
            LsCondition = IIf(IsCondition = "", "", " AND " & IsCondition)
            Return MoDat.DsAmod.Tables("_a_Columns").Select("Tablename='" & GetTableNameFromAppTableName(IsAppTableName) & "' AND " & GetActualVIDcondition() & LsCondition, IsSortingCondition)
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    'gets concrete column
    Public Function GetConcreteColumn(ByVal IsAppTableName As String, ByVal IsColumnName As String) As DataRow()
        Try
            Return MoDat.DsAmod.Tables("_a_Columns").Select("Tablename='" & GetTableNameFromAppTableName(IsAppTableName) & "' AND ColumnName='" & IsColumnName & "' AND " & GetActualVIDcondition())
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    'gets string which represents serializable diagram
    Public Function GetActualDiagramData() As String
        Try
            Dim LoRows() As DataRow = MoDat.DsAmod.Tables("_a_FlowChartData").Select(GetActualVIDcondition)
            Return LoRows(0)("_a_Value")
        Catch ex As Exception
            Debug.Print("CHYBA!!! - ClsFileAmod.GetActualDiagramData")
            Return ""
        End Try
    End Function
    'gets description of version
    Public Function GetDescriptionOfActualVersion() As String
        Try
            Dim LoRows() = GetActualVersion()
            Return LoRows(0)("_a_Description")
        Catch ex As Exception
            Debug.Print("CHYBA!!! - ClsFileAmod.GetDescriptionOfActualVersion")
            Return ""
        End Try
    End Function
    'gets description of unit
    Public Function GetDescriptionOfUnit(ByVal UnitName As String) As String
        Try
            Dim LoRows() = GetUnit(UnitName)
            Return LoRows(0)("_a_Description")
        Catch ex As Exception
            Debug.Print("CHYBA!!! - ClsFileAmod.GetDescriptionOfUnit")
            Return ""
        End Try
    End Function
    'gets description of table 
    Public Function GetDescriptionOfTable(ByVal IsAppTableName As String) As String
        Try
            Dim LoRows() = GetTable(IsAppTableName)
            Return LoRows(0)("_a_Description")
        Catch ex As Exception
            Debug.Print("CHYBA!!! - ClsFileAmod.GetDescriptionOfTable")
            Return ""
        End Try
    End Function
    'gets description of column of table 
    Public Function GetDescriptionOfColumnOfTable(ByVal IsAppTableName As String, ByVal IsColumnName As String) As String
        Try
            Dim LoRows() = GetConcreteColumn(IsAppTableName, IsColumnName)
            Return LoRows(0)("_a_Description")
        Catch ex As Exception
            Debug.Print("CHYBA!!! - ClsFileAmod.GetDescriptionOfColumnOfTable")
            Return ""
        End Try
    End Function
    'gets description of hierarchy
    Public Function GetDescriptionOfHierarchy(ByVal IsTableName As String) As String
        Try
            Dim LoRows() = MoDat.DsAmod.Tables("_Hierarchy").Select("TableName='" & IsTableName & "'")
            Return LoRows(0)("_a_Description")
        Catch ex As Exception
            Debug.Print("CHYBA!!! - ClsFileAmod.GetDescriptionOfHierarchy")
            Return ""
        End Try
    End Function
#End Region
#Region "TRIGGERS"
    '_Tables - update TableName after AppTableName was changed
    Public Function Trigger_TablesUpdateTableNameAfterAppTableName(ByVal IsAppTableName As String) As GeActionResult
        Try
            Dim LoRows() = MoDat.DsAmod.Tables("_Tables").Select("AppTableName= '" & IsAppTableName & "'")
            LoRows(0)("TableName") = GetTableNameFromAppTableName(IsAppTableName)

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    '_Hierarchy - update ParentTable and ForeignKey after AppTableName of table was changed
    Public Function Trigger_HierarchyUpdateParentTableAfterAppTableName(ByVal IsNewParentAppTableName As String, ByVal IsOldParentAppTableName As String) As GeActionResult
        Try
            Dim LoRows() = MoDat.DsAmod.Tables("_Hierarchy").Select("ParentTable= '" & IsOldParentAppTableName & "'")
            If LoRows.Length > 0 Then
                For LiI As Integer = 0 To LoRows.Length - 1
                    LoRows(LiI)("ParentTable") = IsNewParentAppTableName
                    LoRows(LiI)("ForeignKey") = GetForeignKeyForHierarchy(IsNewParentAppTableName)
                Next
                FileWasModified = True
            End If

            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
#End Region
#End Region
#Region "Support functions"
    'gets parsing strings for unique name (of table or column)
    'from "Table_01" --> returns string "Table" and integer 1
    Private Function GetParsingStringsForUniqueName(ByVal IsOriginalString As String, ByRef OsFirstPart As String, ByRef OiSecondPart As Integer, ByRef ObIsNumbering As Boolean) As GeActionResult
        ' ''Dim LiIndex As Integer = 0
        ' ''Dim LbIsNumbering = True
        ' ''Dim LsNewString As String = ""
        ' ''Dim LsFirstPart As String = ""

        ' ''Try
        ' ''    Dim LiLastIndex As Integer = IsOriginalString.LastIndexOf("_")
        ' ''    If LiLastIndex <> -1 Then
        ' ''        LsFirstPart = IsOriginalString.Substring(0, LiLastIndex)
        ' ''        If LiLastIndex < IsOriginalString.Length - 1 Then
        ' ''            Dim LsSecondPart As String = IsOriginalString.Substring(LiLastIndex + 1, IsOriginalString.Length - LiLastIndex - 1)
        ' ''            LiIndex = CType(LsSecondPart, Integer) + 1
        ' ''        End If
        ' ''    Else
        ' ''        LsFirstPart = IsOriginalString
        ' ''        LbIsNumbering = False
        ' ''    End If

        ' ''    OsFirstPart = LsFirstPart
        ' ''    OiSecondPart = LiIndex
        ' ''    ObIsNumbering = LbIsNumbering
        ' ''    Return GeActionResult.kkOk
        ' ''Catch ex As Exception
        ' ''    OsFirstPart = IsOriginalString
        ' ''    OiSecondPart = LiIndex
        ' ''    ObIsNumbering = False
        ' ''    Return GeActionResult.kkError
        ' ''End Try
    End Function
    'gets TableName with prefix "dat_" from AppTableName
    Public Function GetTableNameFromAppTableName(ByVal IsAppTableName As String)
        Return IIf(IsAppTableName <> GsStringNullValue, "dat_" & IsAppTableName, GsStringNullValue)
    End Function
    'gets actual VID condition
    Private Function GetActualVIDcondition() As String
        Return " _a_VID=" & MiActualVID
    End Function
    'gets foreign key for hierarchy
    Private Function GetForeignKeyForHierarchy(ByVal IsParentAppTableName As String) As String
        Return IIf(IsParentAppTableName <> GsStringNullValue, "ID_" & IsParentAppTableName, GsStringNullValue)
    End Function
    'gets main hierarchy name
    Private Function GetMainHierarchyName() As String
        Return "_MainHierarchy"
    End Function
    'create new version in table _a_Version
    Public Function CreateNewVersion(ByRef OiNewVID As Integer) As GeActionResult
        Try
            Dim LiNewVID As Integer = GetLastVersion() + 1 'next version
            OiNewVID = LiNewVID

            'new version in table _a_Version
            If InsertNewVersion(LiNewVID) <> GeActionResult.kkOk Then Throw New Exception
            'new version in table _Settings
            If InsertNewSettings(LiNewVID) <> GeActionResult.kkOk Then Throw New Exception
            'new version in table _a_FlowChartData
            If InsertNewDiagramData(LiNewVID) <> GeActionResult.kkOk Then Throw New Exception

            'if Im here, everything is ok :-)
            OiNewVID = LiNewVID

            FileWasModified = True
            Return GeActionResult.kkOk
        Catch ex As Exception
            Return GeActionResult.kkError
        End Try
    End Function
    'export aMod to xMod
    Public Function ExportToxMod(ByVal IsPath As String) As GeActionResult
        Return IIf(MoDat.ExportToXmod(IsPath) = True, GeActionResult.kkOk, GeActionResult.kkError)
    End Function
#End Region
#End Region

End Class

